package com.mflex.WHSmartWhouseAd.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;

import com.mflex.WHSmartWhouseAd.R;
import com.mflex.WHSmartWhouseAd.adapter.CombinedVehicleAdapter;
import com.mflex.WHSmartWhouseAd.model.CommitCombinedVehicleModel;
import com.mflex.WHSmartWhouseAd.model.CommonRequest;
import com.mflex.WHSmartWhouseAd.model.CombinedVehiclePdaResult;
import com.mflex.WHSmartWhouseAd.model.CombinedVehiclePdaInfo;
import com.mflex.WHSmartWhouseAd.model.ShipmentBoxNoPdaInfo;
import com.mflex.WHSmartWhouseAd.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

//import butterknife.BindView;
//import butterknife.ButterKnife;


public class CombinedVehicleActivity extends BaseActivity implements AdapterView.OnItemClickListener  {
    // 操作人员
    EditText stvOperator;
    // 载具码
    EditText stvVehicleCode;
    // 包号/盘号
    EditText stvPackageNumber;
    // 物料类型
    Spinner SpstorageNo;
    // 列表
    ListView lvList;
    // 清空
    Button buttonClear;
    // 提交
    Button buttonSubmit;

    // loading
    MiniLoadingDialog miniLoadingDialog;
    List<CombinedVehiclePdaResult>CombinedVehicleModelList=new ArrayList<>();
    CommitCombinedVehicleModel model = new CommitCombinedVehicleModel();
    CombinedVehiclePdaInfo TransferVehInput = new CombinedVehiclePdaInfo();
    private String userName;
    private String selectValue;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_combined_vehicle);
//        ButterKnife.bind(this);
        // 弹窗提示
        miniLoadingDialog =WidgetUtils.getMiniLoadingDialog(this,"加载...");
//        id绑定
        stvOperator = findViewById(R.id.stv_Operator);
        stvVehicleCode = findViewById(R.id.stv_VehicleNo);
        stvPackageNumber = findViewById(R.id.stv_PackageNumber);
        SpstorageNo = findViewById(R.id.SpStorageNo);
        lvList = findViewById(R.id.lvList);
        buttonClear = findViewById(R.id.button_clear);
        buttonSubmit = findViewById(R.id.button_submit);
        // 传递数据
        Intent intent = getIntent();
        userName = intent.getStringExtra("User");
        // 视图按键监听器
        stvPackageNumber.setOnKeyListener(this);
        stvVehicleCode.setOnKeyListener(this);
        stvOperator.setOnKeyListener(this);
        buttonSubmit.setOnClickListener(this);
        buttonClear.setOnClickListener(this);
        stvOperator.requestFocus();
        // 下拉框列表
        List<String> options = new ArrayList<>();
        options.add("");
        options.add("元器件");
        options.add("半成品");
        options.add("原材料");
        ArrayAdapter<String> adapter =new ArrayAdapter<String>(this, com.king.zxing.R.layout.support_simple_spinner_dropdown_item,options);
        adapter.setDropDownViewResource(com.xuexiang.xpage.R.layout.support_simple_spinner_dropdown_item);
        SpstorageNo.setAdapter(adapter);
        SpstorageNo.setSelection(0);
        // 获取下拉框当前选择的数据
        SpstorageNo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectValue = parent.getItemAtPosition(position).toString();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_clear:
                CombinedVehicleModelList.clear();
                CombinedVehicleAdapter CombinedVehicleAdapter = new CombinedVehicleAdapter(CombinedVehicleActivity.this,CombinedVehicleModelList);
                lvList.setAdapter(CombinedVehicleAdapter);
                stvPackageNumber.setText("");
                stvVehicleCode.setText("");
                stvOperator.setText("");
                SpstorageNo.setSelection(0);
                stvPackageNumber.requestFocus();
                break;
            case R.id.button_submit:
                saveButtonMd(view);
                break;
            default:
                break;
        }

    }
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && (i == 66 || i == 61)) {
            switch (view.getId()) {
                case R.id.stv_PackageNumber: // 包号/盘号
                     chekPackageNumber();
                    break;
                case R.id.stv_VehicleNo: // 载具号
                    chekVehicleCode();
                    break;
                case R.id.stv_Operator: // 操作人
                    chekOperator();
                    break;
                default:
                    break;
            }
        }
        return false;
    }
    // 扫操作人触发接口
    private void chekOperator() {
        if(StringUtils.isEmpty(stvOperator.getText().toString())) {
            return;
        }
        miniLoadingDialog.show();
        XHttp.get("api/WHSmartWhousePDA/CheckActionUser")
                .params("UserName",stvOperator.getText().toString())
                .syncRequest(false)
                .onMainThread(true)
                .execute(new SimpleCallBack<Boolean>() {
                    @Override
                    public  void  onSuccess(Boolean response) {
                        miniLoadingDialog.dismiss();
                    }
                    @Override
                    public void onError(ApiException e) {
                        miniLoadingDialog.dismiss();
                        stvOperator.setText("");
                        stvOperator.requestFocus();
                        MediaPlayer mp = MediaPlayer.create(CombinedVehicleActivity.this,R.raw.error_voice);mp.start();
                        new MaterialDialog.Builder(CombinedVehicleActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }
                });
    }
    // 扫描载具码触发接口
    private void chekVehicleCode() {
        if(StringUtils.isEmpty(stvVehicleCode.getText().toString())) {
            return;
        }
        if(StringUtils.isEmpty(selectValue)) {
            MediaPlayer mp = MediaPlayer.create(CombinedVehicleActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(CombinedVehicleActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("物料类型未选择")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }
//        miniLoadingDialog.show();
//        XHttp.get("api/WHSmartWhousePDA/TransferCheckVehIsHave")
//                .params("VehiclesName",stvVehicleCode.getText().toString())
//                .params("MaterialType", selectValue)
//                .syncRequest(false)
//                .onMainThread(true)
//                .execute(new SimpleCallBack<Boolean>() {
//                    @Override
//                    public void onSuccess(Boolean response) {
//                        miniLoadingDialog.dismiss();
//                    }
//                    @Override
//                    public void onError(ApiException e) {
//                        miniLoadingDialog.dismiss();
//                        stvVehicleCode.setText("");
//                        stvVehicleCode.requestFocus();
//                        MediaPlayer mp = MediaPlayer.create(CombinedVehicleActivity.this,R.raw.error_voice);mp.start();
//                        new MaterialDialog.Builder(CombinedVehicleActivity.this)
//                                .iconRes(R.drawable.icon_warning)
//                                .title(R.string.tip_warning)
//                                .content(e.getMessage())
//                                .positiveText(R.string.lab_submit)
//                                .show();
//                    }
//                });
    }

//    箱号回车事件触发
    private void chekPackageNumber() {
        // start测试
//        CombinedVehiclePdaResult items = new CombinedVehiclePdaResult();
//        items.setMaterialNo("料号111");
//        items.setLotNo("20241127");
//        items.setQty("100");
//        items.setChangeable("涨缩值");
//        items.setPackOrBoxNumber("bh001");
//        items.setExpDate("时间");
//        items.setOriginVehName("载具");
//        List dataList = new ArrayList<>();
//        dataList.add(items);
//        CombinedVehicleModelList = dataList;
//        CombinedVehicleAdapter CombinedVehicleAdapter = new CombinedVehicleAdapter(CombinedVehicleActivity.this,CombinedVehicleModelList);
//        lvList.setAdapter(CombinedVehicleAdapter);
        // end测试
        if(StringUtils.isEmpty(stvPackageNumber.getText().toString())) {
            MediaPlayer mp = MediaPlayer.create(CombinedVehicleActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(CombinedVehicleActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("包号/盘号未输入")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }
        if(StringUtils.isEmpty(stvOperator.getText().toString())) {
            MediaPlayer mp = MediaPlayer.create(CombinedVehicleActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(CombinedVehicleActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("操作人未输入")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }
        if(StringUtils.isEmpty(stvVehicleCode.getText().toString())) {
            MediaPlayer mp = MediaPlayer.create(CombinedVehicleActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(CombinedVehicleActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("载具号未输入")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }
        if(StringUtils.isEmpty(selectValue)) {
            MediaPlayer mp = MediaPlayer.create(CombinedVehicleActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(CombinedVehicleActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("物料类型未选择")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }
        // 重复扫描卡控
        boolean ischeck = true;
        if(!CombinedVehicleModelList.isEmpty()) {
            for(CombinedVehiclePdaResult item: CombinedVehicleModelList) {
                if(Objects.equals(item.getPackOrBoxNumber(), stvPackageNumber.getText().toString())) {
                    ischeck = false;
                    break;
                }
            }
        }
        if(!ischeck) {
            MediaPlayer mp =MediaPlayer.create(CombinedVehicleActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(CombinedVehicleActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("箱号"+stvPackageNumber.getText().toString()+"在列表中已存在")
                    .positiveText(R.string.lab_submit)
                    .show();
            stvPackageNumber.setText("");
            stvPackageNumber.requestFocus();
            return;
        }
        TransferVehInput.setVehName(stvVehicleCode.getText().toString());
        TransferVehInput.setMType(selectValue);
        TransferVehInput.setCheckPackOrBoxNumber(stvPackageNumber.getText().toString());
        TransferVehInput.setFirstRow(!CombinedVehicleModelList.isEmpty() ? CombinedVehicleModelList.get(0):null);
//        CommonRequest request =new CommonRequest();
//        request.setJson(JsonUtil.toJson(TransferVehInput));
//        String json = JsonUtil.toJson(TransferVehInput);
//        Log.d("1234",json);
        miniLoadingDialog.show();
        XHttp.post("api/WHSmartWhousePDA/TransferCheckVehicles")
                .upJson(JsonUtil.toJson(TransferVehInput))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(150000)
                .execute(new SimpleCallBack<List<CombinedVehiclePdaResult>>() {
                    @Override
                    public  void  onSuccess(List<CombinedVehiclePdaResult>  response) {
                        miniLoadingDialog.dismiss();
                        CombinedVehicleModelList.addAll(response);
                        CombinedVehicleAdapter CombinedVehicleAdapter = new CombinedVehicleAdapter(CombinedVehicleActivity.this,CombinedVehicleModelList);
                        lvList.setAdapter(CombinedVehicleAdapter);
                        stvPackageNumber.setText("");
                        stvPackageNumber.requestFocus();
                    }
                    @Override
                    public void onError(ApiException e) {
                        miniLoadingDialog.dismiss();
                        stvPackageNumber.setText("");
                        stvPackageNumber.requestFocus();
                        MediaPlayer mp =MediaPlayer.create(CombinedVehicleActivity.this,R.raw.error_voice);mp.start();
                        new MaterialDialog.Builder(CombinedVehicleActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }
                });
    }
//    提交
    private void saveButtonMd(View v) {
        if(CombinedVehicleModelList.isEmpty()){
            MediaPlayer mp = MediaPlayer.create(CombinedVehicleActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(CombinedVehicleActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("包号/盘号未输入")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }
        model.setActionUser(stvOperator.getText().toString());
        model.setMType(selectValue);
        model.setVehName(stvVehicleCode.getText().toString());
        model.setTransferVehRowDtos(CombinedVehicleModelList);
//        CommonRequest request =new CommonRequest();
//        request.setJson(JsonUtil.toJson(model));
//        String json = JsonUtil.toJson(model);
//        Log.d("1234",json);
        miniLoadingDialog.show();
        XHttp.post("api/WHSmartWhousePDA/TransferVehSubmit")
                .upJson(JsonUtil.toJson(model))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onSuccess(String response) {
                        miniLoadingDialog.dismiss();
                        XToastUtils.success("提交成功",3000);
                        CombinedVehicleModelList.clear();
                        CombinedVehicleAdapter CombinedVehicleAdapter = new CombinedVehicleAdapter(CombinedVehicleActivity.this,CombinedVehicleModelList);
                        lvList.setAdapter(CombinedVehicleAdapter);
                        stvPackageNumber.setText("");
                        stvOperator.setText("");
                        SpstorageNo.setSelection(0);
                        stvVehicleCode.setText("");
                        stvPackageNumber.requestFocus();
                    }
                    @Override
                    public void onError(ApiException e) {
                        miniLoadingDialog.dismiss();
                        MediaPlayer mp =MediaPlayer.create(CombinedVehicleActivity.this,R.raw.error_voice);mp.start();
                        new MaterialDialog.Builder(CombinedVehicleActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }

                });
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }
}